/* eslint-disable no-undef */
/* eslint-disable camelcase */
import { Toast } from 'antd-mobile'
import axios, { AxiosError } from 'axios'
import { getToken } from './storage'
import history from './history'
import store from '@/store'
import { logout, saveToken } from '@/store/actions/login'
const baseURL = 'http://toutiao.itheima.net/v1_0'
const instance = axios.create({
  baseURL,
  timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    // 如果有token就带上
    const token = getToken()
    if (token.token) {
      config.headers!.Authorization = `Bearer ${token.token}`
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response
  },
  async function (error:AxiosError<{message:string}>) {
    // 对响应错误做点什么
    if (!error.response) {
      Toast.show('网络异常')
      return Promise.reject(error)
    }
    if (error.response.status !== 401) {
      Toast.show('后端错误')
      return Promise.reject(error)
    }
    if (error.response?.status === 401) {
      const { refresh_token } = getToken()
      if (!refresh_token) {
        history.push('/login', { from: history.location.pathname })
        Toast.show('登录信息过期')
        return Promise.reject(error)
      }
      try {
        // 使用refresh_token 去换取新的token
        const res = await axios.put(baseURL + 'authorizations', null,
          {
            headers: {
              Authorization: `Bearer ${refresh_token}`
            }
          })
        // setToken(tokens)
        store.dispatch(saveToken({ token: res.data.data, refresh_token }))
        return instance(error.config)
      } catch (err) {
        // setToken(tokens)
        store.dispatch(logout())
        history.replace('/login', { from: history.location.pathname })
        return Promise.reject(error)
      }
    }
    return Promise.reject(error)
  }
)

export default instance
